<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="mr-2 w-1/4 xl:w-1/5 overflow-hidden bg-white">
      <BasicTree
        :title="t('目录信息')"
        ref="asyncTreeRef"
        search
        toolbar
        :clickRowToExpand="true"
        expandOnSearch
        :treeData="treeData"
        :load-data="onLoadData"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </div>
    <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" v-auth="'areaManager:add'">{{
          t('新增区域')
        }}</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              auth: 'areaManager:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              auth: 'areaManager:delete',
              color: 'error',
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AreaModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, reactive, toRefs } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { BasicTree, TreeActionType, TreeItem } from '/@/components/Tree';
  import { getAreaProvinceList, getAreaList, deleteArea } from '/@/api/system/area';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { uniq } from 'lodash-es';
  import AreaModal from './components/AreaModal.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { t } = useI18n();
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('区域名称'),
      component: 'Input',
      colProps: { xs: 16, md: 8 },
      componentProps: {
        placeholder: t('请输入区域名称'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: t('编号'),
      dataIndex: 'code',
      width: 120,
      sorter: true,
      align: 'left',
    },
    {
      title: t('名称'),
      dataIndex: 'name',
      width: 120,
      sorter: true,
      align: 'left',
    },
    {
      title: t('简拼'),
      dataIndex: 'simpleSpelling',
      width: 120,
      sorter: true,
      align: 'left',
    },
    {
      title: t('快速查询'),
      dataIndex: 'quickQuery',
      width: 120,
      sorter: true,
      align: 'left',
    },
    {
      title: t('级别'),
      dataIndex: 'layer',
      width: 120,
      sorter: true,
      customRender: ({ text }) => {
        switch (text) {
          case 1:
            return t('省');
          case 2:
            return t('市');
          case 3:
            return t('区');
          case 4:
            return t('街道');
        }
      },
    },
    {
      title: t('备注'),
      sorter: true,
      dataIndex: 'remark',
      width: 180,
      align: 'left',
    },
  ];

  const { notification } = useMessage();

  const selectAreaId = ref('');

  const { filterColumnAuth } = usePermission();

  const filterColumns = filterColumnAuth(columns, true);

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: t('行政区域列表'),
    api: getAreaList,
    rowKey: 'id',
    columns: filterColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选区域id
      return { ...params, id: selectAreaId.value };
    },
    useSearchForm: true,
    striped: false,
    actionColumn: {
      width: 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  const treeData = ref<TreeItem[]>([]);
  const asyncTreeRef = ref<Nullable<TreeActionType>>(null);

  function onLoadData(treeNode) {
    return new Promise((resolve: (value?: unknown) => void) => {
      getAreaList({ id: treeNode.id }).then((res) => {
        const asyncTreeAction: TreeActionType | null = unref(asyncTreeRef);
        if (asyncTreeAction) {
          asyncTreeAction.updateNodeByKey(treeNode.key, { children: res });
          asyncTreeAction.setExpandedKeys(
            uniq([treeNode.key, ...asyncTreeAction.getExpandedKeys()]),
          );
        }
        resolve();
        return;
      });
    });
  }

  async function fetch() {
    treeData.value = (await getAreaProvinceList()) as unknown as TreeItem[];
  }

  onMounted(() => {
    fetch();
  });
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
      ...areaInfo,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    deleteArea([record.id]).then((_) => {
      reload({ searchInfo: { id: selectAreaId.value } });
      notification.success({
        message: t('提示'),
        description: t('删除成功'),
      }); //提示消息
    });
  }

  function handleSuccess() {
    reload({ searchInfo: { id: selectAreaId.value } });
  }
  const areaInfo = reactive({
    layer: 1,
    parentId: null,
  });
  function handleSelect(areaId = '', { selectedNodes }) {
    let { layer, parentId } = toRefs(areaInfo);
    layer.value = selectedNodes[0]?.layer + 1 || 1;
    parentId.value = selectedNodes[0]?.id;
    selectAreaId.value = areaId[0] || '';
    reload({ searchInfo: { id: areaId } });
  }
</script>
